package com.mysite.springcloud.demo.web.controller;

import com.mysite.springcloud.demo.api.facade.UserFacade;
import com.mysite.springcloud.demo.api.vo.UserVo;
import com.mysite.springcloud.demo.web.commons.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserFacade userFacade;

    @RequestMapping("/")
    public String login(HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.LOGIN_USER_KEY);
        if (user == null) {
            return "login";
        }
        return "redirect:/index";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Boolean doLogin(String username, String password, HttpSession session) {
        UserVo user = userFacade.getUserByUsername(username);
        if (user == null) {
            return false;
        }
        if(!user.getPassword().equals(password)){
            return false;
        }
        session.setAttribute(Constants.LOGIN_USER_KEY, user);
        return true;
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}
